package com.xdwanj.smartcity.ui.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.xdwanj.smartcity.ui.NewsActivity;
import com.xdwanj.smartcity.data.bean.BannerData;
import com.xdwanj.smartcity.data.bean.News;
import com.xdwanj.smartcity.databinding.FragmentHomeBinding;
import com.xdwanj.smartcity.ui.adapter.IndexNewsAdapter;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private FragmentHomeBinding binding;

    private EditText searchBox;
    private Banner indexBanner;

    // 新闻相关UI
    private TabLayout newsType;
    private ListView newsList;

    //适配器
    IndexNewsAdapter indexNewsAdapter;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 将此Fragment的所有组件存入此类的私有成员
        initComponent();
        // 初始化搜索框，添加点击事件
        initSearchBox();
        // 设置Banner图片
        initBanner();
        // 设置新闻相关
        setNewsList();
        return root;
    }

    /**
     * 将此Fragment的所有组件存入此类的私有成员
     */
    private void initComponent() {
        searchBox = binding.searchBox;
        indexBanner = binding.indexBanner;

        newsType = binding.item;
        newsList = binding.newsList;
    }

    /**
     * 初始化搜索框，添加点击事件
     */
    private void initSearchBox() {
        searchBox.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                InputMethodManager imm = ((InputMethodManager) textView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE));

                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(textView.getApplicationWindowToken(),1);
                }

                return true;
            }
            return false;
        });
    }

    /**
     * 设置Banner图片
     */
    private void initBanner() {
        homeViewModel.getBanners().observe(getViewLifecycleOwner(), new Observer<List<BannerData>>() {
            @Override
            public void onChanged(List<BannerData> banners) {
                List<String> tempImageUrl = new ArrayList<>();
                for (int i = 0;i < banners.size();i++) {
                    tempImageUrl.add(banners.get(i).getAdvImg());
                }
                indexBanner.setImages(tempImageUrl);
                indexBanner.setDelayTime(2000);
                indexBanner.setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        Glide.with(context).load(path).into(imageView);
                    }
                });
                indexBanner.start();
            }
        });
    }

    /**
     * 设置新闻类别选择事件
     */
    private void setNewsTypeEvent() {
        newsType.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 设置新闻列表
     */
    private void setNewsList() {
        homeViewModel.getNews().observe(getViewLifecycleOwner(), new Observer<List<News>>() {
            @Override
            public void onChanged(List<News> news) {

                newsList.setVerticalScrollBarEnabled(true);
                newsList.setNestedScrollingEnabled(true);
                indexNewsAdapter = new IndexNewsAdapter(getContext(),news);
                newsList.setAdapter(indexNewsAdapter);
                newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        Intent intent = new Intent(getActivity(), NewsActivity.class);
                        intent.putExtra("html",news.get(i).getContent());
                        startActivity(intent);
                    }
                });
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}